using Microsoft.EntityFrameworkCore;
using RAG.Domain.Repositories;
using RAG.Infrastructure.Data;

namespace RAG.Infrastructure.Repositories;

/// <summary>
/// EF Core通用仓储实现
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
public class EfRepository<T> : IRepository<T> where T : class
{
    protected readonly RagAIDbContext _context;
    protected readonly DbSet<T> _dbSet;

    public EfRepository(RagAIDbContext context)
    {
        _context = context;
        _dbSet = context.Set<T>();
    }

    /// <summary>
    /// 根据ID查询
    /// </summary>
    public async Task<T?> GetByIdAsync(Guid Id)
    {
        return await _dbSet.FindAsync(Id);
    }

    /// <summary>
    /// 查询所有
    /// </summary>
    public async Task<IEnumerable<T>> GetAllAsync()
    {
        return await _dbSet.ToListAsync();
    }

    /// <summary>
    /// 创建
    /// </summary>
    public async Task<T> CreatedAsync(T entity)
    {
        var result = await _dbSet.AddAsync(entity);
        await _context.SaveChangesAsync();
        return result.Entity;
    }

    /// <summary>
    /// 更新
    /// </summary>
    public async Task<T> UpdateAsync(T entity)
    {
        _dbSet.Update(entity);
        await _context.SaveChangesAsync();
        return entity;
    }

    /// <summary>
    /// 删除
    /// </summary>
    public async Task DeleteAsync(Guid Id)
    {
        var entity = await GetByIdAsync(Id);
        if (entity != null)
        {
            _dbSet.Remove(entity);
            await _context.SaveChangesAsync();
        }
    }
}

